package cn.itsource.hbc.org.controller;

import cn.itsource.hbc.org.domain.Department;
import cn.itsource.hbc.org.query.DepartmentQuery;
import cn.itsource.hbc.org.service.IDepartmentService;
import cn.itsource.utils.AjaxResult;
import cn.itsource.utils.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Department department){

        try {
           if(department.getId()!=null){
               departmentService.update(department);
           }else {
               departmentService.save(department);
           }
           return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();

            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());

        }

    }

    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){

        try {
            departmentService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败"+ e.getMessage());

        }


    }


    @GetMapping("/{id}")
    public Department loadById(@PathVariable("id") Long id){

        return departmentService.loadById(id);
    }


    @GetMapping
    public List<Department> loadAll(){

        return departmentService.loadAll();
    }

    @PostMapping
    public PageResult<Department>queryPage(@RequestBody DepartmentQuery query){

    return departmentService.queryPage(query);
    }


    @PatchMapping
    public AjaxResult allDelete(@RequestBody Long[] ids){
        // 传回来的数据是id的一个数组，将业务交给service'
        try {
                departmentService.allDelete(ids);
                return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()+"操作失败");
        }

    }










}
